<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="130px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="项目名称">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_name"
                placeholder="输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="审批类型">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.type"
                placeholder="选择审批类型">
                <el-option label="签约优惠" :value="1"></el-option>
                <el-option label="结算优惠" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优惠金额">
              <el-input v-input-limit="2" @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.discount_amount_min" placeholder="输入优惠金额"></el-input>
            </el-form-item>
            <el-form-item label="项目编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_number"
                placeholder="输入项目编号"></el-input>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="项目品牌">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.brand_id"
                  placeholder="选择项目品牌">
                  <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="项目类型">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.store_type_id" placeholder="选择项目类型">
                  <el-option v-for="item in storeTypeList" :key="item.id" :label="item.store_type_name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="优惠后成本利润率">
                <el-input v-input-limit="2" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.remaining_cost_profit_ratio_min" placeholder="输优惠后成本利润率"></el-input>
              </el-form-item>
              <el-form-item label="优惠前成本利润率">
                <el-input v-input-limit="2" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.cost_profit_ratio_min" placeholder="输入优惠前成本利润率"></el-input>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" class="form-width"
                  v-model="formSearch.create_at" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="创建人">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.name"
                  placeholder="选择创建人">
                  <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <!--  :disabled="userInfo.position_id != 2" -->
          <el-button type="primary" @click="addDiscountFunc"
            v-if="$isPer(permission, ['discount_add'])">发起优惠审批</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <div class="tab-box">
          <el-tabs v-model="formSearch.to_do" @tab-click="onSearch(1)">
            <el-tab-pane label="全部" name="0"></el-tab-pane>
            <el-tab-pane label="待处理" name="1"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="list-top-box-right">
          <p class="list-top-box-left">
            已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
          </p>
          <el-button :disabled="tableData.length == 0" type="primary" @click="exportVisible = true"
            v-if="$isPer(permission, ['discount_exportDiscountApprovalExcel'])">导出优惠审批列表</el-button>
          <el-button type="primary" :disabled="YHSPFunc" @click="YHSPclickFunc(1)"
            v-if="$isPer(permission, ['discount_examine'])">审核优惠审批</el-button>
          <el-button type="primary" :disabled="YHFSFunc" @click="YHSPclickFunc(14)"
            v-if="$isPer(permission, ['discount_discountReviewPassed2'])">复审优惠审批</el-button>
          <el-button type="primary" :disabled="SPZFFunc" @click="discountInvalidationFunc"
            v-if="$isPer(permission, ['discount_discountInvalidation'])">审批作废</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="pageLoading">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData"
          @selection-change="handleSelectionChange" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="140px" prop="" fixed="left" label="ID">
            <template slot-scope="scope">
              <el-button @click.stop="goToDetailFunc(scope.row)" type="text">{{ $assemblyListNo('YHSP', scope.row.id)
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_glxm')" min-width="180px" fixed="left" prop="project_name"
            label="项目名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_xmbh')" min-width="130px" fixed="left" prop="project_number"
            label="项目编号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_xmpp')" min-width="120px" fixed="left" prop="brand_name"
            label="项目品牌" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
                {{ scope.row.brand_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_xmlx')" min-width="120px" prop="store_type_name" label="项目类型"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_shzt')" min-width="100px" prop="customer_director_review"
            label="审批状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.customer_director_review == 1">审核中</span>
              <span v-if="scope.row.customer_director_review == 2">审核通过</span>
              <span v-if="scope.row.customer_director_review == 3">审核拒绝</span>
              <span v-if="scope.row.customer_director_review == 4">已废弃</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_splx')" min-width="120px" prop="type" label="审批类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.type == 1 ? '签约优惠' : '结算优惠' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_yhje')" min-width="110px" prop="" label="优惠金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.discount_amount ? scope.row.discount_amount + '元' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_yhhlrje')" min-width="130px" prop="" label="优惠后利润金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.remaining_profit_amount ? scope.row.remaining_profit_amount + '元' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_yhhcblrl')" min-width="140px" prop="" label="优惠后成本利润率"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.remaining_cost_profit_ratio ? scope.row.remaining_cost_profit_ratio + '%' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_yhqlrje')" min-width="130px" prop="" label="优惠前利润金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.profit_amount ? scope.row.profit_amount + '元' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_yhqcblrl')" min-width="140px" prop="" label="优惠前成本利润率"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.cost_profit_ratio ? scope.row.cost_profit_ratio + '%' : '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_shjjly')" min-width="180px" prop="reason_refusal" label="审批拒绝理由"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.reason_refusal || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_cjr')" min-width="120px" prop="name" label="创建人"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('yh_cjsj')" min-width="180px" prop="created_at" label="创建时间"
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 导出优惠审批列表 -->
    <el-dialog :modal-append-to-body="false" title="导出优惠审批字段选择" :visible.sync="exportVisible" width="680px"
      :before-close="exportCloseFunc">
      <el-checkbox class="checkbox-item" v-model="allChecked" @change="allCheckedChangeFunc">全选</el-checkbox>
      <div v-loading="exportLoading">
        <div class="export-scroll">
          <el-checkbox-group v-model="exportrVal">
            <el-checkbox class="checkbox-item" v-for="(item, index) in exportArr" :key="index" :label="item.label"
              border></el-checkbox>
          </el-checkbox-group>
        </div>
        <p v-if="exportUrl">导出文件链接：<el-button @click="$openUrlFunc(exportUrl[0])" type="text">{{
          exportUrl[1]
        }}</el-button></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSubmitFunc">提交</el-button>
        <el-button @click="exportCloseFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from "@/api/common";
import brandApi from "@/api/brandApi";
import storeTypeApi from "@/api/storeTypeApi";
import { getUserInfo } from "@/utils/auth";
import discountApi from "@/api/discountApi";
import adminApi from "@/api/adminApi";
import { discountApprovalFideldArr } from '@/utils/exportField';
export default {
  name: "discountApproval",
  data() {
    return {
      // 导出用户列表
      allChecked: false,//是否全选字段
      exportLoading: false,//导出loading
      exportVisible: false,//导出弹窗
      exportUrl: '',//导出url
      exportrVal: [],//导出勾选字段
      exportArr: discountApprovalFideldArr,//导出字段数组

      userInfo: "",
      tableData: [],
      formSearch: {
        to_do: '0',
      },
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      addLoading: false,
      pageLoading: false,
      multipleSelection: [],
      brandList: [],//品牌
      storeTypeList: [],//门店类型
      adminList: [],//客户经理
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
    // 优惠审批 && this.userInfo.position_id == 1
    YHSPFunc() {
      if (this.multipleSelection.length == 1 && this.multipleSelection[0].customer_director_review == 1
        && this.multipleSelection[0].review_status == 10
        && (this.multipleSelection[0].is_retrial == 2 || this.multipleSelection[0].is_retrial == 3)
      ) {
        return false;
      } else {
        return true;
      }
    },
    // 优惠复审 && this.userInfo.position_id == 14
    YHFSFunc() {
      if (this.multipleSelection.length == 1 && this.multipleSelection[0].customer_director_review == 1
        && this.multipleSelection[0].is_retrial == 3 && this.multipleSelection[0].review_status == 20
      ) {
        return false;
      } else {
        return true;
      }
    },
    // 审批作废
    SPZFFunc() {
      if (this.multipleSelection.length == 1 && this.multipleSelection[0].customer_director_review != 4) {
        return false;
      } else {
        return true;
      }
    },
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.hrefQueryFunc(() => {
      this.onSearch();
    })
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.hrefQueryFunc(() => {
      this.discountApprovalList();//审批列表
      this.getBrandList();//品牌
      this.getStoreTypeList();//门店类型
      this.getAdminList();//客户经理
    })
    this.userInfo = getUserInfo();

  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 优惠审批详情
    goToDetailFunc(item) {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/discountDetail",
        query: {
          id: item.id
        }
      })
    },
    // 跳转判断的
    hrefQueryFunc(cb) {
      let query = this.$route.query;
      if (JSON.stringify(query) != "{}") {
        this.formSearch.project_name = query.project_name || '';//筛选项目名
        this.formSearch.to_do = query.to_do || '0';//是否待处理
      }
      cb && cb();
    },
    // 导出列表确认
    exportSubmitFunc() {
      let exportrVal = this.exportrVal;//已勾选
      let exportArr = this.exportArr;//所有字段
      let formSearch = this.formSearch;//筛选项
      if (!exportrVal.length) {
        this.$message({
          type: 'warning',
          message: "请勾选需要导出的字段"
        })
        return;
      }
      let field_list = [];//提交列表
      exportrVal.forEach(item => {
        let index = exportArr.findIndex(child => {
          return item == child.label;
        })
        if (index != -1) {
          field_list.push(exportArr[index].value);
        }
      })
      this.exportDiscountApprovalExcel({
        field_list,
        type: formSearch.type || '',
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        customer_director_review: formSearch.customer_director_review || '',
        create_at_start: formSearch.create_at ? formSearch.create_at[0] : '',
        create_at_end: formSearch.create_at ? formSearch.create_at[1] : '',
        name: formSearch.name || '',
        discount_amount_min: formSearch.discount_amount_min || '',
        remaining_cost_profit_ratio_min: formSearch.remaining_cost_profit_ratio_min || '',
        cost_profit_ratio_min: formSearch.cost_profit_ratio_min || '',
      })
    },
    exportDiscountApprovalExcel(obj) {
      this.exportLoading = true;
      discountApi.exportDiscountApprovalExcel(obj).then(res => {
        console.log(res, "导出优惠审批列表")
        this.exportLoading = false;
        if (res.code == 200) {
          this.exportUrl = res.data;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 导出字段全选
    allCheckedChangeFunc(e) {
      let exportrVal = [];
      let exportArr = this.exportArr;
      if (e) {
        exportArr.forEach(item => {
          exportrVal.push(item.label);
        })
        this.exportrVal = exportrVal//已选择字段
      } else {
        this.exportrVal = exportrVal//已选择字段
      }
    },
    // 关闭导出弹窗
    exportCloseFunc() {
      this.exportVisible = false;
      this.allChecked = false;
      this.exportrVal = [];
      this.exportUrl = '';
    },
    // 优惠审批
    YHSPclickFunc(type) {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: 'discountDetail',
        query: {
          id: this.multipleSelection[0].id,
          examine: true
        }
      })
      // this.$router.push({
      //   path: type == 1 ? '/shbjyhCom' : '/fsbjyhCom',
      //   query: {
      //     id: this.multipleSelection[0].id,
      //     is_retrial: type == 1 ? this.multipleSelection[0].is_retrial : '',
      //   }
      // })
    },
    // 发起审批
    addDiscountFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addDiscount',
      })
    },
    // table单行点击
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 客户经理
    getAdminList() {
      adminApi.getAdminList({
        page: 1,
        num: 999,
        position_id_arr: [2],
        identity: 1
      }).then(res => {
        console.log(res, "客户经理")
        if (res.code == 200) {
          this.adminList = res.data.list;
        }
      })
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 9999,
          keyword: "",
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        })
        .catch(() => { });
    },
    // 门店类型列表
    getStoreTypeList() {
      storeTypeApi.getStoreTypeList({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "门店类型列表")
        if (res.code == 200) {
          this.storeTypeList = res.data.list;
        }
      })
    },
    // 审批列表
    discountApprovalList() {
      this.pageLoading = true;
      let formSearch = this.formSearch;
      discountApi.discountApprovalList({
        page: this.page,
        num: this.num,
        to_do: formSearch.to_do || 0,
        type: formSearch.type || '',
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        customer_director_review: formSearch.customer_director_review || '',
        create_at_start: formSearch.create_at ? formSearch.create_at[0] : '',
        create_at_end: formSearch.create_at ? formSearch.create_at[1] : '',
        name: formSearch.name || '',
        discount_amount_min: formSearch.discount_amount_min || '',
        remaining_cost_profit_ratio_min: formSearch.remaining_cost_profit_ratio_min || '',
        cost_profit_ratio_min: formSearch.cost_profit_ratio_min || '',
      }).then(res => {
        this.pageLoading = false;
        console.log(res, "审批列表")
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.discountApprovalList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // 优惠审批作废
    discountInvalidationFunc() {
      let multipleSelection = this.multipleSelection;
      this.$confirm('此操作将作废该审批, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        discountApi.discountInvalidation({
          discount_id: multipleSelection[0].id
        }).then(res => {
          console.log(res, "作废优惠审批")
          if (res.code == 200) {
            this.onSearch(1);
          }
          this.$message({
            type: res.code == 200 ? 'success' : 'warning',
            message: res.code == 200 ? '操作成功' : res.message
          });
        })
      }).catch(() => {

      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss'
</style>